package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishPage;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@Slf4j
@RequestMapping("/admin/dish")
public class DishController {
    @Autowired
    DishService dishService;

    @Autowired
    RedisTemplate redisTemplate;


    @Transactional
    @PostMapping

    public Result saveWithFlavor(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品:{}", dishDTO);
        dishService.saveWithFlavor(dishDTO);
        String key = "dish_" + dishDTO.getCategoryId();
        redisTemplate.delete(key);//将数据全部删除，下次查询再将数据库的数据存入redis

        return Result.success();

    }

    @GetMapping("/page")

    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO) {
        PageResult pageResult = dishService.page(dishPageQueryDTO);


        return Result.success(pageResult);
    }


    @DeleteMapping

    public Result delete(@RequestParam ArrayList<Long> ids) {
        log.info("批量删除菜品");
        log.info(String.valueOf(ids));
        for (Long id : ids) {
            Long categoryId = GetById(id).getData().getCategoryId();
            String key = "dish_" + categoryId;
            redisTemplate.delete(key);
        }
        dishService.delete(ids);

        return Result.success();
    }

    @GetMapping("/{id}")

    public Result<DishVO> GetById(@PathVariable Long id) {
        log.info("根据ID查询菜品回显:{}", id);
        DishVO dishVO = dishService.getById(id);
        return Result.success(dishVO);
    }

    @PutMapping

    public Result update(@RequestBody DishVO dishVO) {
        log.info("修改菜品信息:{}", dishVO);
        dishService.update(dishVO);
        Set delete = redisTemplate.keys("dish_*");
        redisTemplate.delete(delete);

        return Result.success();
    }

    @PostMapping("status/{status}")
    public Result updateStatus(@PathVariable Integer status,Integer id){

        dishService.updateStatus(status,id);
        return Result.success();
    }


}
